$(document).ready(function(){	  

	var tree = $('#treeStructureFull');
	InitTree(tree);
	
	//---------------------
	var pane = $('#LeftPane');
	
	pane.find('.ui-layout-content').scroll(function(){	
		$.cookie('expanded_list_pos', this.scrollTop, { path: '<?=Mozg::Router('http')->Create('module=admin&ctrl=structure');?>'});	
	}).each(function(){
		this.scrollTop = $.cookie('expanded_list_pos');
	});	
	
	pane.find('.hd .icon-toggle-tree').click(function (e) { 
		var lists = tree.find('ul');
		var isClosedAll = lists.find('.minus, .minus_end').size() > 0 ? false : true;

		changeExpandedList('all', isClosedAll); 

		isClosedAll ? ReloadElement(tree.find('li.root')) : HideTree(tree.find('li.root > ul'));
		
		return false;
	});
	
});

function InitTree(tree)
{
	tree.find('span').one("click", function(){ 
		ChangeElements($(this).parent('li')); 
	});

	tree.disableSelection();

	tree.find('.cat-block').one('mouseenter', function(){
		InitTreeLeaf($(this));
	}).droppable({
		scope: 'category',
		tolerance: 'touch',
		drop: function(ev, ui) {
			
			var targetLink = $(this).find('a.leaf');
			
			if (!confirm('<?php echo Mozg_Lang::_('MOVE_CATEGORY_INTO'); ?> " '+targetLink.html()+'"?')) return false;
	
	        drag_id = ui.draggable.parent().data('id');
			drop_id = $(this).data('id');
	
			$.getJSON(
				'<?=Mozg::Router('http')->Create('module=admin&ctrl=structure&action=move');?>',
				{drag: drag_id, drop: drop_id},
				function (data) {
						HandleResponseJSON(data, function(data){
							window.location.href = window.location.href;
						});
				}
			);
	
			return false;
		}
	});	
}

function InitTreeLeaf(leaf)
{
	var id = leaf.data('id');
	var html = $('#treeIcons').html();
	html = html.replace(/%7Bcat%7D/ig, id).replace(/%7Bsubcat%7D/ig, id);

	leaf.append(html);
	
	var elemClickHref = '<?=Mozg::Router('http')->Create('module=admin&ctrl=structure&action=list&cat={cat}');?>';	
	var link = leaf.find('a.leaf');
	link.click(function(e){
		if(e.ctrlKey) 
		{
			return true;
		}

		window.location.href = elemClickHref.replace(encodeURIComponent('{cat}'), id);
		return false;
	});	
	
	leaf.find('.doc').draggable({
		scope: 'category',
		helper: function(){
			return $('<div class="move-container"><?php echo Mozg_Lang::_('moving'); ?>: '+link.html()+'</div>').appendTo('body');			
		},			
		cursorAt: {top:2, left:-10},
		zIndex: 1000,
		iframeFix: true,
		addClasses: false
	});		
}

function ReloadElement(elem)
{
	$.getJSON(
			'<?=Mozg::Router('http')->Modify('module=admin&ctrl=structure&action=subtree');?>',
			{subcat: elem.children('.cat-block').data('id')},
			function (data) {
					HandleResponseJSON(data, function(data){
						
						var isRoot = elem.hasClass('root');
						var opened = (elem.hasClass('minus') || elem.hasClass('minus_end'));
						var isLast = (elem.html() == elem.parent().children('li:last').html());
						var addClass = '';
						
						elem.children('ul').remove();
						elem.removeClass('plus plus_end minus minus_end');
						elem.children('span').remove();							
						
						var s = $(data).first('ul');
						
						if (!isRoot)
						{
							if (s.size())
							{	
								if (!opened) s.hide();
								
								elem.prepend('<span></span>');
	
								addClass = opened ? 'minus' : 'plus';
								addClass += isLast ? '_end' : '';
							}	
							else
							{
								addClass = isLast ? 'end' : '';
							}
						}	
						
						elem.append(s);
						
						elem.addClass(addClass);
						InitTree(elem);
					});
			}
		);	
}

function ChangeElements(elem)
{
    var addClass, getClass, setClass, isAdd = false;

    if (elem.hasClass('plus') || elem.hasClass('plus_end'))
    {
            getClass = 'plus';
            setClass = 'minus';
            isAdd = true;
    }
    else
    {
            getClass = 'minus';
            setClass = 'plus';
    }

    if (elem.hasClass(getClass+'_end')) addClass = '_end';
    else addClass = '';

    elem.removeClass(getClass+addClass);
    elem.addClass(setClass+addClass);

    changeExpandedList(elem.children('.cat-block').data('id'), isAdd);
    
    var sublist = elem.children('ul');
    
    if (isAdd)
    {	
	    if (sublist.size())
	    {	
	    	sublist.show();
	    }
	    else
	    {
	    	ReloadElement(elem);
	    	return;
	    }	
    }
    else
    {
    	sublist.hide();
    }
	
    elem.children('span').one("click", function () { ChangeElements(elem) });
}

function changeExpandedList(id, isAdd)
{
	var list = [];
	if ($.cookie('expanded_list'))
	{	
		var list = $.cookie('expanded_list').split('_');
	}

	if (id == 'all') list = [];
	
	var indexPlus = $.inArray(id, list);
	var indexMinus = $.inArray('-'+id, list);
	
	if (isAdd) 
	{
		if (indexPlus == -1)
		{
			list.push(id);
		}	

		if (indexMinus != -1)
		{
			list.splice(indexMinus, 1);
		}		
	}
	else {
		if (indexMinus == -1)
		{
			list.push('-'+id);
		}
		
		if (indexPlus != -1)
		{
			list.splice(indexPlus, 1);
		}	
	}	

	$.cookie('expanded_list', list.join('_'), { path: '<?=Mozg_Router::Get('http')->Create(array('module' => 'admin'));?>'});
}

function HideTree(elem)
{
	var leafs = elem.find('li');
	leafs.filter('.minus').removeClass('minus').addClass('plus');
	leafs.filter('.minus_end').removeClass('minus_end').addClass('plus_end');	
	elem.find('ul').hide();
}